<template>
	<view class="login-class" ref="loginElement" :style="[{backgroundImage:'url('+backgroundImageUrl+')'}]">
		
		<view class="status_bar" v-if="!isMiniProgram" style="height: var(--status-bar-height); width: 100%; "></view>
		<view class="header-container" :style="headerStyle">
			<view class="tn-flex justify-between items-center">
				<tn-icon name="close tn-pl" size="50" class="setting-class" @click="doHome"></tn-icon>
				<tn-icon name="set-fill tn-pr" size="50" class="setting-class" @click="doSetting"></tn-icon>
			</view>
		</view>
		
		<view class="logo-box-class">
		    <view class="logo-class" ref="logoElement" :style="[{backgroundImage:'url('+logoImageUrl+')'}]"></view>
		</view>
		<form>
			<view class="login-input-class">
				<tn-input v-model="userInfo.userName" placeholder="请输入用户名" class="input-class tn-shadow-md tn-round tn-text-bold" 
					:placeholder-style="placeholderStyle" :border="false" >
					<template #prefix>
						<tn-icon name="my-simple" size="50" color="#FFFFFF"   />
					</template>
				</tn-input>
				
				<tn-input v-model="userInfo.passWord" placeholder="请输入密码" class="input-class tn-shadow-md tn-round tn-text-bold" 
					:placeholder-style="placeholderStyle"  :border="false" type="password">
					<template #prefix>
					  <tn-icon name="lock" size="50" color="#FFFFFF"  />
					</template>
				</tn-input>
				
				<tn-input v-model="userInfo.captcha" placeholder="请输入验证码" class="input-class tn-shadow-md tn-round tn-text-bold"
					:placeholder-style="placeholderStyle"  :border="false" v-show="store.state.isShowCaptcha">
					<template #prefix>
					  <tn-icon name="eye" size="50" color="#FFFFFF"  />
					</template>
					<template #suffix>
					  <tn-button class="captcha-class" :disabled="store.state.isDisabledCaptchaButton" @click="getCaptcha">
						  {{ store.state.isDisabledCaptchaButton ? `${store.state.countDown}秒` : '获取验证码' }}
					  </tn-button>
					</template>
				</tn-input>
				<button class="button-class" @click="doLogin">登录</button>
			</view>
		</form>
	</view>
	<tn-modal ref="modalRef" />
<!-- 	<tn-popup v-model="showPopup">
	    <view class="tn-p-lg" style="width: 90vw;" > 
			<tn-title title="当前设备信息不一样,需要短信验证" mode="vLine" assist-color="#61e6be" class="tn-p-sm tn-text-bold" color="tn-color-black"/>
			<tn-input v-model="captcha" placeholder="请输入验证码" class="tn-mt-lg">
			    <template #suffix>
			      <tn-button class="captcha-class">获取验证码</tn-button>
			    </template>
			  </tn-input>
			  <button class="button-class tn-mt-lg" >确定</button>
		</view>
	</tn-popup> -->
	
	<!-- 578710459088965 龙心 -->
	<!-- 543432941621317 药都汇 -->
	<!-- 586262499766341 九洲康 -->
	<!-- 613893403672645 瑞弘-->
	<!-- 687712971804741 鲁康-->
	<!-- 690239481647173 -->
	<wrap-version-update id="690239481647173" v-if="isAppInstance" :api-url="apiUpdateUrl"></wrap-version-update>
	
</template>

<script setup>
	import WrapVersionUpdate from '@/uni_modules/wrap-version-update/components/wrap-version-update/wrap-version-update.nvue'

	import { ref ,reactive,onMounted,nextTick  } from 'vue'
	import { postLogin,postUserInfo,postCall,postNoCall,postSendCaptcha   } from '@/api/index.js'
	import { toastMessage } from '@/utils/toast.js'
	import { createParams } from '@/utils/utils.js'
	import md5 from "js-md5";
	
	import {userAllDataStore} from '@/stores'
	const store = userAllDataStore();
	console.log()
	// console.log(JSON.parse(uni.getStorageInfoSync("HTTP")));
	const apiUpdateUrl = uni.getStorageSync('HTTP')+"/v1Check";
	console.log(apiUpdateUrl);
	const loginElement = ref(null);
	const logoElement = ref(null);
	const  isAppInstance = ref(true);
	const captcha = ref("");
	if(process.env.UNI_PLATFORM === 'h5'){
		isAppInstance.value = false;
	}
	const showPopup = ref(false);
	
	// const  isAppInstance  =  inject('isAppInstance');
	// console.log(isAppInstance);
	// import { } from	const mobile = ref('')
	const  backgroundImageUrl  =  ref('');
	const logoImageUrl = ref('');
	const placeholderStyle = reactive({
		color : "#FFFFFF"
	})
	const userInfo = reactive({
		userName : "",
		passWord : "",
		captcha : ""
	})

	let timer = null;
	
	const startCountdown = () => {
		console.log(timer);
	  if (timer) {
		clearInterval(timer);
	  }
	  timer = setInterval(() => {
		if (store.state.countDown > 0) {
			store.state.countDown --;
			store.state.isDisabledCaptchaButton = true;
		} else {
		  console.log("000000000000000000");
		  clearInterval(timer);
		  store.state.countDown = 60;
		  store.state.isDisabledCaptchaButton = false;
		}
	  }, 1000);
	};
	 
	const systemInfo = reactive({});
	const sysInfo = reactive({});
	const ip = ref("127.0.0.1");
	const getUserUUID = async () =>{
		let params = {};
		params.P_PROC_NAME = "PROC_APP_DO_USER_CHECK";
		params.P_LGNNAME = userInfo.userName;
		params.P_ACTION = "USERCHECK";
		await postNoCall(params).then(res=>{
			if(res){
				if(res.code===200){
					let uuidInfo = res.data.DATASET[0];
					if(uuidInfo!=null &&  uuidInfo.uuid!=null && uuidInfo.uuid!="" ){
						if(uuidInfo.uuid!=systemInfo.deviceId){
							store.state.isShowCaptcha = true;
						}
					}
				}
			}
		})
	}
	
	const getCaptcha = () =>{
		store.state.isDisabledCaptchaButton = true;
		let params = {};
		params.P_LGNNAME = userInfo.userName;
		postSendCaptcha(params).then(res=>{
			if(res.code ===200){
				if(res.data.status!=null && res.data.status==0){
					toastMessage("发送成功！");
				}
			}
		})
		startCountdown();
		
	}
	const headerStyle = ref({});

	const isMiniProgram = ref(false);

	onMounted(()=>{
		const loginUserInfo = uni.getStorageSync("LOGINUSER");
		if(loginUserInfo){
			Object.assign(userInfo,loginUserInfo);
		}
		Object.assign(systemInfo,uni.getSystemInfoSync());
		
		// 判断是否为小程序
		isMiniProgram.value = process.env.UNI_PLATFORM === 'mp-weixin';
		
		// 获取胶囊按钮位置信息
		if (isMiniProgram.value) {
			const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			headerStyle.value = {
				height: menuButtonInfo.height + 'px',
				marginTop: (menuButtonInfo.top ) + 'px'
			};
		}else{
			headerStyle.value = {
				height:  '44px',
				marginTop: '10px'
			};
		}
		
		// console.log('======================================');
		// uni.request({
		//   url: 'https://api.ipify.org?format=json',
		//   success: (res) => {
		// 	  console.log(res);
		// 	  ip.value = res.data.ip +"";
		// 		// ip = res.data.ip;
		//   },
		//   fail: (err) => {
		// 		console.log(err);
		// 	  ip.value = "127.0.0.l"; 
		//   }
		// })
		if (timer) {
			if(store.state.isDisabledCaptchaButton.value){
				startCountdown();
			}else{
				clearInterval(timer);
			}
		}

		
		//设置背景
		const httpUrl = uni.getStorageSync("HTTP");
		backgroundImageUrl.value  =  httpUrl+'/static/bg.jpg';
		logoImageUrl.value = httpUrl + '/static/logo.png'

	})
	const buttonClass = {
		bgColor	:"inear-gradient(to right, #47A6C2, #3F90D4)"
	}
	const userData = ref({});
	let doLogin = async () =>{
		
		uni.setStorageSync("LOGINUSER", userInfo);
		if(!store.state.isShowCaptcha){
			await getUserUUID();
		}
		if((store.state.isShowCaptcha && userInfo.captcha.length==6) || !store.state.isShowCaptcha){
			let loginParams = {};
			loginParams.P_LGNNAME = userInfo.userName;
			loginParams.P_PWD = md5(userInfo.passWord);
			loginParams.P_CAPTCHA = userInfo.captcha;
			postLogin(loginParams).then(res=>{
				uni.setStorageSync("token", res.data.token);
				postUserInfo().then(res=>{
					if(res){
						if(res.code===200){
							userInfo.captcha = "";
							uni.setStorageSync("LOGINUSER", userInfo);
							if(uni.getStorageSync("CLIENTINFO")){
								uni.removeStorageSync("CLIENTINFO")
							}
							
							userData.value = res.data.DATASET[0];
							if(userData.value){
								uni.setStorage({
								    key: 'USERINFO',
								    data: res.data.DATASET[0],
								    success: function () {
								        doGetClientWarnData();
								    }
								});
							}else{
								uni.setStorage({
								    key: 'USERINFO',
								    data: res.data.DATASET[0],
								    success: function () {
								        uni.redirectTo({
								        	url: '/pages/index/index'
								        });
								    }
								});
							}
							let params = {};
							params["P_PROC_NAME"] = "PROC_APP_DO_LOGIN_ADD_HIS";
							params["P_ACTION"] = "LOGIN";
							params["P_IP"] = ip.value;
							params["P_LGNNAME"] = userInfo.userName;
							postCall(Object.assign(params,createParams(systemInfo))).then(res=>{
									
							})	
							store.state.isShowCaptcha = false;
						}else{
							toastMessage("当前账号未绑定部门信息！！")
						}
					}
					
				})
			})
		}
		
		
		
	}
	
	const modalRef = ref()
	const clientWarnData = reactive([]);
	
	let doGetClientWarnData = () =>{
		clientWarnData.length = 0;
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_CLASSIFY";
		params["P_ACTION"] = "CLIENTWARN";	
		params["P_CLIENTID"] = userData.value.staffid;
		params["P_STAFFID"] = userData.value.staffid;
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					Object.assign(clientWarnData,res.data.DATASET);
					if(clientWarnData.length>0){
						console.log("8888");
						let info = "";
						for(let i=0;i<clientWarnData.length;i++){
							info = info + clientWarnData[i].titleinfo + "\n";
						}
						
						modalRef.value?.showModal({
						  title: '温馨提示',
						  content: info,
						  showCancel: false,
						  confirm: () => {
							  uni.setStorage({
							      key: 'USERINFO',
							      data: userData.value,
							      success: function () {
							          uni.redirectTo({
							          	url: '/pages/index/index'
							          });
							      }
							  });
							},
						})
					}else{
						uni.setStorage({
						    key: 'USERINFO',
						    data: userData.value,
						    success: function () {
						        uni.redirectTo({
						        	url: '/pages/index/index'
						        });
						    }
						});
					}
				}else{
					uni.setStorage({
					    key: 'USERINFO',
					    data: userData.value,
					    success: function () {
					        uni.redirectTo({
					        	url: '/pages/index/index'
					        });
					    }
					});
				}
			}
		})
	}
	
	let doHome = () =>{
		uni.setStorageSync("index",0);
		uni.redirectTo({
			url: '/pages/index/index'
		});
		
	}
	
	// loginElement.value.style.backgroundImage =  `url('${backgroundImageUrl.value}')`;
	// logoElement.value.style.backgroundImage  =  `url('${logoImageUrl.value}')`;
	
	const doRegister = ()=>{
		uni.redirectTo({
			url: '/pages/register/register'
		});
	}
	const doSetting = ()=>{
		uni.redirectTo({
			url: '/pages/setting/setting'
		});
	}
</script>

<style scoped>

.login-class{
	height: 100vh;
	overflow: hidden;
	/* background: url('/static/bg.jpg'); */
	/* background: url('http://60.205.187.65:9533/lx/static/bg.jpg'); */
	background-position: center;
	background-size: cover;
	position: fixed;
	width: 100vw;
}

.header-container {
	width: 100%;
	display: flex;
	align-items: center;
}

.header-container .tn-flex {
	width: 100%;
	height: 100%;
}

/* .align-center {
	align-items: center;
} */

.logo-box-class{
	height: 40vh;
	display: flex;
	justify-content: center; /* 水平居中 */
	align-items: center; /* 上下居中对齐 */
}
.logo-class{
	width: 150px; /* 设置 logo 宽度 */
	height: 150px; /* 高度自适应 */
	/* background-image: url('/static/logo.png'); */ /* 设置背景图片 */
	/* background-image: url('http://60.205.187.65:9533/lx/static/logo.png'); */
	background-size: contain; /* 图片自适应容器大小 */
	background-position: center; /* 图片居中显示 */
	background-repeat: no-repeat; /* 背景图不重复 */
}
.login-input-class{
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
.input-class{
	width: 80vw;
	margin-bottom: 20px;
	border-radius: 40px;
	
}
.button-class{
	width: 80vw;
	/* padding: 15px !important; */
	border-radius: 40px !important;
	color: #FFFFFF !important;
	background: linear-gradient(to right, var(--beginColor),var(--endColor)) !important;
	border: 0px solid rgba(0, 0, 0, 0.2) !important;
}

.button-class::after{
	border: 0px solid rgba(0, 0, 0, 0.2) !important;
}

.span-class{
	color: #FFFFFF;
}
.register-class{
	margin-top: 3vh;
}
.setting-class{
	color: var(--settingColor);
}
.captcha-class{
	color: var(--titleColor);
	background-color: var(--settingColor);
}
</style>
